package com.example.homework9;

import android.content.Context;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.net.Uri;

public class MusicHelper {
    private MediaPlayer mediaPlayer;
    private Context context;
    private  final  int[]musics = new int[]{};//音乐
    private int musicIndex = 0;
    private boolean prepared = false;
    public  MusicHelper(Context context){
        this.context = context;
        createMediaplayer();
    }

    private void createMediaplayer() {
        mediaPlayer = new MediaPlayer();
        mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);

    }

    public void play(){
        if(mediaPlayer.isPlaying()){
            return;
        }

        if (prepared){
            mediaPlayer.start();
            return;
        }

        try{
            mediaPlayer.setDataSource(context, Uri.parse("android.resource://com.example.allione/"+musics[musicIndex]))
        }catch (Exception e){
            e.printStackTrace();
        }

        mediaPlayer.prepareAsync();
        mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
            @Override
            public void onPrepared(MediaPlayer mp) {
                mp.start();
                prepared = true;
            }
        });



    }
//暂停
        public void pause(){
        if(!mediaPlayer.isPlaying()){
            return;
            }
        mediaPlayer.pause();
        }
    //下一首
        public void next(){
            musicIndex = musicIndex + 1;
            musicIndex = musicIndex % musics.length;
            destroy();
            createMediaplayer();
            play();
    }

    public void destroy() {
        if (mediaPlayer == null){
            return;
        }
        mediaPlayer.stop();
        mediaPlayer.release();
        mediaPlayer = null;
        prepared = false;
    }
}
